<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexIntegralRequest;
use App\Http\Requests\StoreIntegralRequest;
use App\Http\Requests\UpdateIntegralRequest;
use App\Http\Resources\IntegralResource;
use App\Models\Integral;
use Illuminate\Support\Facades\Auth;

class IntegralController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(IndexIntegralRequest $request)
    {
        $query = Integral::query();

        $query->when($request->filled('name'), function ($query) use ($request) {
            $name = $request->input('name');
            return $query->where(function ($subquery) use ($name) {
                $subquery->where('name', 'like', "%$name%");
            });
        })->when($request->filled('reward_type'), function ($query) use ($request) {
            $reward_type = $request->input('reward_type');
            return $query->where('status', $reward_type);
        });

        $data = $query->with('intergralabel')->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response =  IntegralResource::collection($data);
        $total = $response->total();
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreIntegralRequest $request, Integral $integral)
    {
        $integral->fill($request->input());
        $integral->saveOrFail();
        return $this->success('添加成功', $integral);
    }

    /**
     * Display the specified resource.
     */
    public function show(Integral $integral)
    {
        $data = new IntegralResource($integral->load('intergralabel'));
        return $this->success('查询成功', $data);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Integral $integral)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateIntegralRequest $request, Integral $integral)
    {
        $integral->fill($request->input());
        $integral->saveOrFail();
        return $this->success('更新成功', $integral);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Integral $integral)
    {
        $this->authorize('delete', $integral);
        $integral->delete();
        return $this->success('删除成功', $integral);
    }
}
